package com.my.xq.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.my.xq.domain.YwhSettingsJQTreeNode;
import com.my.xq.domain.entity.CourtYwhSettings;
import com.my.xq.domain.vo.DoorCount;
import com.my.xq.repository.CourtYwhSettingsRepository;
import com.my.xq.repository.DoorplateRepository;
import com.sskj.common.tree.TreeNode;
import com.sskj.common.tree.TreeUtil;
import com.sskj.core.annotation.ControllerLogExeTime;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/ywh/settings")
public class CourtYwhSettingsServiceImpl {
	@Autowired
	CourtYwhSettingsRepository courtYwhSettingsRepository;

	@Autowired
	DoorplateRepository doorplateRepository;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/findOne", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "查询设置")
	public CourtYwhSettings findOne(String id) {
		return courtYwhSettingsRepository.get(id);
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/update", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "更新设置")
	public boolean update(String id, int countMember) {
		try {
			CourtYwhSettings entity = courtYwhSettingsRepository.get(id);
			if (entity != null) {
				entity.setCountMember(countMember);
				courtYwhSettingsRepository.save(entity);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/getAll")
	@ApiOperation(value = "获取楼栋单元户数", httpMethod = "GET")
	public Page<YwhSettingsJQTreeNode> findCountDoorByCourtId(String courtId) {
		List<DoorCount> rtn = new ArrayList<DoorCount>();
		List<CourtYwhSettings> entities = courtYwhSettingsRepository.findAllByCourtId(courtId);
		if (entities == null || entities.size() == 0) {
			List<Object[]> rs = doorplateRepository.findCountDoorByCourtId(courtId);
			if (rs != null && rs.size() > 0) {
				String building = null;
				int totalDoors = 0;
				List<DoorCount> tempDCs = new ArrayList<DoorCount>();
				DoorCount doorCountOfBuilding = null;
				for (Object[] o : rs) {
					DoorCount dc = new DoorCount();
					dc.setCountOfUnit(Integer.valueOf(String.valueOf(o[0])));
					dc.setCourtId(String.valueOf(o[1]));
					dc.setBuilding(String.valueOf(o[2]));
					dc.setUnit(String.valueOf(o[3]));

					if (building == null) {
						tempDCs.add(dc);
						building = dc.getBuilding();
						totalDoors = dc.getCountOfUnit();
					} else {
						if (building.equals(dc.getBuilding())) {
							totalDoors = totalDoors + dc.getCountOfUnit();
							tempDCs.add(dc);
						} else {
							doorCountOfBuilding = new DoorCount();
							doorCountOfBuilding.setBuilding(building);
							doorCountOfBuilding.setCountOfBuilding(totalDoors);
							doorCountOfBuilding.setCourtId(dc.getCourtId());
							rtn.add(doorCountOfBuilding);
							for (DoorCount dcTemp : tempDCs) {
								rtn.add(dcTemp);
							}
							tempDCs.clear();
							building = dc.getBuilding();
							totalDoors = dc.getCountOfUnit();
							tempDCs.add(dc);
						}
					}
				}
				if (tempDCs.size() > 0) {
					doorCountOfBuilding = new DoorCount();
					doorCountOfBuilding.setBuilding(building);
					doorCountOfBuilding.setCountOfBuilding(totalDoors);
					doorCountOfBuilding.setCourtId(courtId);
					rtn.add(doorCountOfBuilding);
					for (DoorCount dcTemp : tempDCs) {
						rtn.add(dcTemp);
					}
					tempDCs.clear();
				}
				String parentId = null;
				for (DoorCount dc : rtn) {
					CourtYwhSettings entity = new CourtYwhSettings();
					entity.setCourtId(dc.getCourtId());
					entity.setBuilding(dc.getBuilding());
					entity.setUnit(dc.getUnit());
					if (parentId != null && dc.getUnit() != null) {
						entity.setParentId(parentId);
					}
					if (dc.getUnit() == null) {
						entity.setTotalDoors(dc.getCountOfBuilding());
						entity.setType("B");
					} else {
						entity.setTotalDoors(dc.getCountOfUnit());
						entity.setType("U");
					}
					courtYwhSettingsRepository.save(entity);
					if (dc.getUnit() == null) {
						parentId = entity.getId();
					}
				}
				entities = courtYwhSettingsRepository.findAllByCourtId(courtId);
			}
		}

		List<YwhSettingsJQTreeNode> nodes = buildJQTreeNode(entities);
		Page<YwhSettingsJQTreeNode> page = new PageImpl<YwhSettingsJQTreeNode>(nodes);

		return page;
	}

	@SuppressWarnings("rawtypes")
	private List<YwhSettingsJQTreeNode> buildJQTreeNode(List<CourtYwhSettings> list) {

		List<YwhSettingsJQTreeNode> nodes = null;
		if (list != null) {
			nodes = new ArrayList<YwhSettingsJQTreeNode>();
			Map<String, YwhSettingsJQTreeNode> map = new HashMap<String, YwhSettingsJQTreeNode>();
			for (CourtYwhSettings entity : list) {
				YwhSettingsJQTreeNode node = new YwhSettingsJQTreeNode();
				String parentId = entity.getParentId();
				node.setId(entity.getId());
				node.setParentId(parentId);
				node.setParent(parentId);
				node.setBuilding(entity.getBuilding());
				node.setUnit(entity.getUnit());
				node.setCountMember(entity.getCountMember());
				node.setTotalDoors(entity.getTotalDoors());
				node.setType(entity.getType());
				node.setIsLeaf(true);

				map.put(node.getId(), node);
				nodes.add(node);
			}
			Collection<YwhSettingsJQTreeNode> values = map.values();
			for (YwhSettingsJQTreeNode node : values) {
				String parentId = node.getParentId();
				String tempParentId = parentId;
				int level = 0;
				while (StringUtils.isNotEmpty(tempParentId)) {
					YwhSettingsJQTreeNode temp = map.get(tempParentId);
					temp.setIsLeaf(false);
					if (temp != null) {
						level++;
						tempParentId = temp.getParentId();
					}
				}
				node.setLevel(level);
			}

			List<TreeNode> treeList = TreeUtil.build(list);
			List<YwhSettingsJQTreeNode> result = new ArrayList<YwhSettingsJQTreeNode>();
			iterator(treeList, result, map);
			return result;

		}
		return null;
	}

	@SuppressWarnings({ "rawtypes" })
	private void iterator(List<? extends TreeNode> list, List<YwhSettingsJQTreeNode> result,
			Map<String, YwhSettingsJQTreeNode> map) {

		if (list != null && !list.isEmpty()) {
			for (TreeNode tree : list) {
				String id = tree.getId();
				YwhSettingsJQTreeNode ywhSettingsJQTreeNode = map.get(id);
				result.add(ywhSettingsJQTreeNode);
				@SuppressWarnings("unchecked")
				List<TreeNode> children = tree.getChildren();
				if (children != null && !list.isEmpty()) {
					iterator(children, result, map);
				}
			}
		}
	}

}
